using Application.Abstractions.Messaging;
using Domain.Todos;
using Domain.Todos.Specifications;
using Microsoft.EntityFrameworkCore;
using SharedKernel;

namespace Application.Todos.GetPending;

/// <summary>
/// 获取待完成待办事项查询处理器
/// </summary>
internal sealed class GetPendingTodosQueryHandler(ITodoItemRepository todoRepository)
    : IQueryHandler<GetPendingTodosQuery, IEnumerable<TodoResponse>>
{
    public async ValueTask<Result<IEnumerable<TodoResponse>>> Handle(GetPendingTodosQuery query, CancellationToken cancellationToken)
    {
        // 使用规约模式查询待完成的待办事项
        var specification = new PendingTodosSpecification(query.UserId);
        List<TodoItem> todos = await todoRepository.ApplySpecification(specification)
            .ToListAsync(cancellationToken: cancellationToken);

        IEnumerable<TodoResponse> response = todos.Select(todo => new TodoResponse
        {
            Id = todo.Id,
            UserId = todo.UserId,
            Description = todo.Description,
            Priority = todo.Priority,
            DueDate = todo.DueDate,
            Labels = todo.Labels,
            IsCompleted = todo.IsCompleted,
            CreatedAt = todo.CreatedAt,
            CompletedAt = todo.CompletedAt
        });

        return Result.Success(response);
    }
}
